<template>
  <div class="wh-baidu-wraper">
    <div class="wh-baidu" id="wh-map-component-baidu"></div>
    <div class="wh-baidu-infoWindow" ref="wh-baidu-infoWindow">
      <div class="wh-baidu-infoWindow-title">
        <p>
          {{currentInfo.title || '提示'}}
        </p>
        <img @click="onCloseInfoWindow" src="../assets/close.png" alt="">
      </div>
      <div class="wh-baidu-infoWindow-content">
        {{currentInfo.content || '内容'}}
      </div>
      <div class="wh-baidu-infoWindow-place">
        <div class="wh-baidu-infoWindow-bottom"></div>
      </div>

    </div>
    <div class="wh-geode-path-infoWindow" ref="wh-geode-path-infoWindow"></div>
  </div>
</template>

<script>
import loadScript from '../common/loadScript.js'
export default {
  data() {
    return {
      BMap: null,
      map: null,
      infoWindow: null,
      currentInfo: {},
      THREE: null,
      BMapLib: null,
      luShuArr: [],
      pointArr: [],
      pathListArr: []

    }
  },
  props: {
    loadedMap: {
      type: Function,
      default: null
    },
  },
  methods: {
    //  加载地图
    loadMap (options) {

      console.log('创建百度地图');
      return new Promise((resolve, reject) => {
        if(!options.loadConfig) {
          console.error('未配置地图加载所需的必要配置');
          reject('未配置地图加载所需的必要配置')
        }
        if (!options.loadConfig.key && !options.loadConfig.customUrl) {
          console.warn('未配置百度ak')
          reject('未配置百度ak')
        }

        const apiHost = 'http://api.map.baidu.com/getscript'
        const version = options.loadConfig.version || '3.0'
        const ak = options.loadConfig.key
        const t = new Date().getTime()
        const url = options.loadConfig.customUrl?options.loadConfig.customUrl:`${apiHost}?v=${version}&ak=${ak}&services=&t=${t}`

        loadScript('BMap', url).then(() => {
          this.BMap = BMap
          const mapConfig = options.mapConfig?options.mapConfig:{}
          this.map = new BMap.Map('wh-map-component-baidu', {
            enableMapClick: false,
            minZoom: mapConfig.minZoom || 3,
            maxZoom: mapConfig.maxZoom || 20
          })
          if (!mapConfig.center) {
            mapConfig.center = [116.404, 39.915]
          }
          if (!mapConfig.zoom) {
            mapConfig.zoom = 5
          }

          this.map.centerAndZoom(new BMap.Point(mapConfig.center[0], mapConfig.center[1]), mapConfig.zoom )

          this.map.enableScrollWheelZoom();

          //  使用自定义瓦片图层
          if (options.loadConfig.tileUrl) {
            var tileLayer = new BMap.TileLayer()
            tileLayer.getTilesUrl = (tileCoord, zoom) => {
              let tileX = tileCoord.x
              let tileY = tileCoord.y
              return this.getTileUrl(options.loadConfig.tileUrl, tileX, tileY, zoom)
            }
            this.map.addTileLayer(tileLayer)
          }
          // 设置边界
          if (options.mapConfig.bounds && options.mapConfig.bounds.length === 2) {
            require('../common/AreaRestriction_min.js')
            var b = new BMap.Bounds(new BMap.Point(options.mapConfig.bounds[0][0], options.mapConfig.bounds[0][1]),new BMap.Point(options.mapConfig.bounds[1][0], options.mapConfig.bounds[1][1]));
            try {
            	BMapLib.AreaRestriction.setBounds(this.map, b);
            } catch (e) {
            	alert(e);
            }
          }
          this.map.addEventListener('click', this.onClickMap)
          this.initInfoWindow()
          this.loadedMap(this.map)
          resolve(this.map)

        }).catch(err => {
          console.log(err);
        })
      })
    },
    getTileUrl (url, tileX, tileY, zoom) {
      return `${url}?qt=vtile&x=${tileX}&y=${tileY}&z=${zoom}&styles=pl`
    },
    initInfoWindow () {
      this.infoWindow = new BMap.InfoWindow(this.$refs['wh-baidu-infoWindow'], {
        offset: new BMap.Size(-15, 40)
      })
    },
    onCloseInfoWindow () {
      this.infoWindow.close();
      this.currentInfo = {}
    },
    loadMarker (markerList) {
      console.log('加载 marker');
      for (var i = 0; i < markerList.length; i++) {
        var markerOptions = markerList[i].options?markerList[i].options:{}

        var size = [markerOptions.width || 28, markerOptions.height || 28]
        var offfset = new BMap.Size(0, -size[1]/2)
        if (markerOptions.offset) {
          offfset = new BMap.Size(markerOptions.offset[0], markerOptions.offset[1])
        }
        var icon = new BMap.Icon(
          markerOptions.icon || require('../assets/marker/marker-6.png'),
          new BMap.Size(size[0], size[1]),
          {
            imageSize: new BMap.Size(size[0], size[1]),
            imageOffset:  new BMap.Size(0, 0)
          }
        )
        markerOptions.icon = icon
        markerOptions.zIndex = markerOptions.zIndex || 12
        // markerOptions.opacity = markerOptions.opacity || 1
        // // markerOptions.offset = offfset
        for (var j = 0; j < markerList[i].list.length; j++) {
          var marker = new BMap.Marker(new BMap.Point(markerList[i].list[j].position[0], markerList[i].list[j].position[1]), {
           icon: markerOptions.icon,
           offset: offfset
          });
          marker.properties = {
            showInfoWindow: markerOptions.showInfoWindow,
            customInfoWindow: markerOptions.customInfoWindow,
            isInLine: markerOptions.isInLine,
            isInPolygon: markerOptions.isInPolygon,
            ...markerList[i].list[j].properties
          }
          marker.setZIndex(markerOptions.zIndex)
          marker.addEventListener('click', this.onClickMarker)
          this.map.addOverlay(marker)
        }
      }
    },
    loadPolygon (polygonList) {

      console.log('加载 polygon');
      for (var i = 0; i < polygonList.length; i++) {
        var polygonOptions = polygonList[i].options?polygonList[i].options:{}
        polygonOptions.strokeColor = polygonOptions.lineColor || '#00B2D5'
        polygonOptions.strokeWeight = polygonOptions.lineWidth || 2
        polygonOptions.strokeOpacity = polygonOptions.lineOpacity || 1
        polygonOptions.strokeStyle = polygonOptions.lineStyle || 'solid'
        polygonOptions.fillColor = polygonOptions.color || '#00B2D5'
        polygonOptions.fillOpacity = polygonOptions.opacity || 0.5
        // polygonOptions.zIndex = polygonOptions.zIndex || 10
        const path = this.formatterPath(polygonList[i].path)
        var polygon = new BMap.Polygon(
          path,
          {
            ...polygonOptions
          }
        )
        polygon.properties = {
          showInfoWindow: polygonOptions.showInfoWindow,
          customInfoWindow: polygonOptions.customInfoWindow,
          ...polygonList[i].properties
        }
        polygon.addEventListener('click', this.onClickPolygon)
        this.map.addOverlay(polygon)
      }
    },
    loadPath (config) {
      if (!this.THREE) {
        this.THREE = require('../common/three.module.min.js')
      }
      if (!this.BMapLib) {
        this.BMapLib = require('../common/LuShu.js')
      }

      var options = config.options?config.options:{}
      // 起点
      var startSymbol = {
        icon: require('../assets/marker/start.png'),
        width: 28,
        height: 28,
        offset: [0, 0]
      }

      if (options.start && options.start.icon) {
        startSymbol.icon = options.start.icon
      }
      if (options.start && options.start.width) {
        startSymbol.width = options.start.width
      }
      if (options.start && options.start.height) {
        startSymbol.height = options.start.height
      }
      if (options.start && options.start.offset) {
        startSymbol.offset = options.start.offset
      }
      const startIcon = new BMap.Icon(
        startSymbol.icon,
        new BMap.Size(startSymbol.width, startSymbol.height),
        {
          imageSize: new BMap.Size(startSymbol.width, startSymbol.height),
          imageOffset:  new BMap.Size(0, 0)
        }
      )
      // 终点
      var endSymbol = {
        icon: require('../assets/marker/end.png'),
        width: 28,
        height: 28,
        offset: [0, 0]
      }
      if (options.end && options.end.icon) {
        endSymbol.icon = options.end.icon
      }
      if (options.end && options.end.width) {
        endSymbol.width = options.end.width
      }
      if (options.end && options.end.height) {
        endSymbol.height = options.end.height
      }
      if (options.end && options.end.offset) {
        endSymbol.offset = options.end.offset
      }
      const endIcon = new BMap.Icon(
        endSymbol.icon,
        new BMap.Size(endSymbol.width, endSymbol.height),
        {
          imageSize: new BMap.Size(endSymbol.width, endSymbol.height),
          imageOffset:  new BMap.Size(0, 0)
        }
      )
      // 图标
      var pointSymbol = {
        icon: require('../assets/marker/car.png'),
        width: 28,
        height: 28,
        offset: [0, 0]
      }
      if (options.point && options.point.icon) {
        pointSymbol.icon = options.point.icon
      }
      if (options.point && options.point.width) {
        pointSymbol.width = options.point.width
      }
      if (options.point && options.point.height) {
        pointSymbol.height = options.point.height
      }
      if (options.point && options.point.offset) {
        pointSymbol.offset = options.point.offset
      }
      const pointIcon = new BMap.Icon(
        pointSymbol.icon,
        new BMap.Size(pointSymbol.width, pointSymbol.height),
        {
          imageSize: new BMap.Size(pointSymbol.width, pointSymbol.height),
          imageOffset:  new BMap.Size(0, 0)
        }
      )
      //  线条样式
      var pathStyle = {
        color: 'red',
        width: 5,
        defaultColor: '#00D3FC',
        speed: 80, // m/s
        autoMove: false,
        loop: false
      }
      if (options.line && options.line.defaultColor) {
        pathStyle.defaultColor = options.line.defaultColor
      }
      if (options.line && options.line.width) {
        pathStyle.width = options.line.width
      }
      if (options.line && options.line.color) {
        pathStyle.color = options.line.color
      }
      if (options.speed) {
        pathStyle.speed = options.speed
      }
      if (options.autoMove) {
        pathStyle.autoMove = options.autoMove
      }
      if (options.loop) {
        pathStyle.loop = options.loop
      }


      for (var i = 0; i < config.list.length; i++) {
        this.pathListArr.push([config.list[i].path[1], config.list[i].path[0]])
        if (options.start) {
          let startMarker = new BMap.Marker(new BMap.Point(config.list[i].path[0][0], config.list[i].path[0][1]), {
           icon: startIcon,
           offset: new BMap.Size(startSymbol.offset[0], startSymbol.offset[1])
          });
          this.map.addOverlay(startMarker)
        }
        if (options.point) {
          let rotation = this.getPointRotation(config.list[i].path[1], config.list[i].path[0])
          let pointMarker = new BMap.Marker(new BMap.Point(config.list[i].path[0][0], config.list[i].path[0][1]), {
           icon: pointIcon,
           offset: new BMap.Size(pointSymbol.offset[0], pointSymbol.offset[1]),
           rotation: rotation
          });
          pointMarker.properties = {
            index: i
          }
          pointMarker.addEventListener('click', (e) => {
            this.onClickPoint(e, pathStyle)
          })
          this.pointArr.push(pointMarker)
          this.map.addOverlay(pointMarker)
        }
        if (options.end) {
          let endMarker = new BMap.Marker(new BMap.Point(config.list[i].path[config.list[i].path.length - 1][0], config.list[i].path[config.list[i].path.length - 1][1]), {
           icon: endIcon,
           offset: new BMap.Size(endSymbol.offset[0], endSymbol.offset[1]),
          });
          this.map.addOverlay(endMarker)
        }


        // var sy1 = new BMap.Symbol(BMap_Symbol_SHAPE_BACKWARD_OPEN_ARROW, {
        //     scale: 0.6,//图标缩放大小
        //     strokeColor:'#fff',//设置矢量图标的线填充颜色
        //     strokeWeight: '2',//设置线宽
        // });
        // var icons1 = new BMap.IconSequence(sy1, '10', '30');
        let path = new BMap.Polyline(this.formatterPath(config.list[i].path), {
          strokeColor: pathStyle.defaultColor,
          strokeOpacity:1,
          strokeWeight:pathStyle.width,
          enableMassClear:true,
          // icons: [icons]
        });
        path.properties = {
          ...config.list[i].properties
        }
        path.addEventListener('click', this.onClickPath)
        let lushu = new BMapLib.LuShu(this.map, this.formatterPath(config.list[i].path), {
          autoView:false,//是否开启自动视野调整，如果开启那么路书在运动过程中会根据视野自动调整
          icon: pointIcon,
          speed: pathStyle.speed,
          color: pathStyle.color,
          width: pathStyle.width,
          loop: true,
          landmarkPois: [],
          enableRotation:true, //是否设置marker随着道路的走向进行旋转
        });
        this.luShuArr.push(lushu)
        this.map.addOverlay(path)
      }
      if (options.point && options.autoMove) {
        for (var i = 0; i < this.luShuArr.length; i++) {
          this.onClickPoint(this.pointArr[i], pathStyle)
        }
      }
    },
    loadSpecialPath (config) {

      if (!this.BMapLib) {
        this.BMapLib = require('../common/LuShu.js')
      }

      var options = config.options?config.options:{}
      // 起点
      var startSymbol = {
        icon: require('../assets/marker/start.png'),
        width: 28,
        height: 28
      }

      if (options.start && options.start.icon) {
        startSymbol.icon = options.start.icon
      }
      if (options.start && options.start.width) {
        startSymbol.width = options.start.width
      }
      if (options.start && options.start.height) {
        startSymbol.height = options.start.height
      }
      const startIcon = new BMap.Icon(
        startSymbol.icon,
        new BMap.Size(startSymbol.width, startSymbol.height),
        {
          imageSize: new BMap.Size(startSymbol.width, startSymbol.height),
          imageOffset:  new BMap.Size(0, 0)
        }
      )
      // 终点
      var endSymbol = {
        icon: require('../assets/marker/end.png'),
        width: 28,
        height: 28
      }
      if (options.end && options.end.icon) {
        endSymbol.icon = options.end.icon
      }
      if (options.end && options.end.width) {
        endSymbol.width = options.end.width
      }
      if (options.end && options.end.height) {
        endSymbol.height = options.end.height
      }
      const endIcon = new BMap.Icon(
        endSymbol.icon,
        new BMap.Size(endSymbol.width, endSymbol.height),
        {
          imageSize: new BMap.Size(endSymbol.width, endSymbol.height),
          imageOffset:  new BMap.Size(0, 0)
        }
      )
      //  线条样式
      var pathStyle = {
        color: 'red',
        width: 5,
        defaultColor: '#00D3FC',
        speed: 80, // m/s
      }
      if (options.line && options.line.defaultColor) {
        pathStyle.defaultColor = options.line.defaultColor
      }
      if (options.line && options.line.width) {
        pathStyle.width = options.line.width
      }
      if (options.line && options.line.color) {
        pathStyle.color = options.line.color
      }
      if (options.speed) {
        pathStyle.speed = options.speed
      }

      for (var i = 0; i < config.list.length; i++) {
        let startMarker = new BMap.Marker(new BMap.Point(config.list[i].path[0][0], config.list[i].path[0][1]), {
         icon: startIcon,
         offset: new BMap.Size(0, -startSymbol.height/2)
        });
        this.map.addOverlay(startMarker)

        let endMarker = new BMap.Marker(new BMap.Point(config.list[i].path[config.list[i].path.length - 1][0], config.list[i].path[config.list[i].path.length - 1][1]), {
         icon: endIcon,
         offset: new BMap.Size(0, -endSymbol.height/2)
        });
        this.map.addOverlay(endMarker)
        let path = new BMap.Polyline(this.formatterPath(config.list[i].path), {
          strokeColor: pathStyle.defaultColor,
          strokeOpacity:1,
          strokeWeight:pathStyle.width,
          enableMassClear:true,
        });
        this.setSegmentationMarker(this.formatterPath(config.list[i].path), config.list[i].properties.pointCount)

        this.map.addOverlay(path)
      }
    },
    setSegmentationMarker (path, count) {
      let distanceAll = 0
      for (var i = 0; i < path.length; i++) {
        if (path[i+1]) {
          distanceAll += Number(this.map.getDistance(path[i+1], path[i]))
        }
      }
      let pointDistance = distanceAll / count
      // console.log(distanceAll);
      let j = 0
      let distanceBefore = 0
      let deviceList = []
      this._move(path[j], path[j+1], this.linear, j, path, pointDistance, distanceBefore, deviceList);


    },
    //初始坐标，目标坐标，当前的步长，总的步长
    linear (initPos, targetPos, currentCount, count) {
      var b = initPos, c = targetPos - initPos, t = currentCount,
      d = count;
      return c * t / d + b;
    },
    _move (initPos,targetPos,effect, i, path, pointDistance, distanceBefore, deviceList) {

      //当前的帧数
      var currentCount = 0
      //步长，米/秒
      const timer = 10
      let step = 1000 / (800 / timer)
      //初始坐标
      let _projection = this.map.getMapType().getProjection()
      let init_pos = _projection.lngLatToPoint(initPos)
      //获取结束点的(x,y)坐标
      let target_pos = _projection.lngLatToPoint(targetPos)
      //总的步长
      let count = Math.round(this._getDistance(init_pos, target_pos) / step);
        //如果小于1直接移动到下一点
        if (count < 1) {
             this._moveNext(++i, path, pointDistance, distanceBefore, deviceList);
            return;
        }
        //两点之间匀速移动
        let _intervalFlag = setInterval(() => {
        //两点之间当前帧数大于总帧数的时候，则说明已经完成移动
          if (currentCount >= count) {
              clearInterval(_intervalFlag);
              //移动的点已经超过总的长度
            if(i > path.length){
              return;
            }
            this.distanceAll
            //运行下一个点
            this._moveNext(++i, path, pointDistance, distanceBefore, deviceList);
          }else {
            currentCount++;
            var x = effect(init_pos.x, target_pos.x, currentCount, count),
                y = effect(init_pos.y, target_pos.y, currentCount, count),
                pos = _projection.pointToLngLat(new BMap.Pixel(x, y));
            //设置marker
            if(currentCount == 1){
                var proPos = null;
                if(i - 1 >= 0){
                    proPos = path[i - 1];
                }
            }
            //正在移动
            // console.log('x', x);
            // console.log('y', y);
            // pointMarker.setPosition(pos)
            let distance = this.map.getDistance(initPos, pos)
            let distanceAll = distanceBefore + distance
            if (Math.abs(distanceAll - pointDistance * (deviceList.length+1)) < 5) {
              deviceList.push(pos)
            }
            // console.log(distanceAll);
          }
      },timer);
    },
    /**
     * 移动到下一个点
     * @param {Number} index 当前点的索引.
     * @return 无返回值.
     */
    _moveNext (index, path, pointDistance, distanceBefore, deviceList) {
        if (index < path.length - 1) {
            distanceBefore += this.map.getDistance(path[index], path[index - 1])
            this._move(path[index], path[index + 1], this.linear, index, path, pointDistance, distanceBefore, deviceList);
        } else {
          console.log('结束');
          console.log(deviceList);
          for (var i = 0; i < deviceList.length; i++) {

            let pointMarker = new BMap.Marker(deviceList[i]);
            this.map.addOverlay(pointMarker)
          }
        }
    },
    /**
     * 计算两点间的距离
     * @param {Point} poi 经纬度坐标A点.
     * @param {Point} poi 经纬度坐标B点.
     * @return 无返回值.
     */
    _getDistance (pxA, pxB) {
        return Math.sqrt(Math.pow(pxA.x - pxB.x, 2) + Math.pow(pxA.y - pxB.y, 2));
    },

    formatterPath (arr) {
      var newArr = []
      for (var i = 0; i < arr.length; i++) {
        var point = new BMap.Point(arr[i][0], arr[i][1])
        newArr.push(point)
      }
      return newArr
    },
    getPointRotation (lonlat2, lonlat1) {
      var lon1=this.THREE.MathUtils.degToRad(lonlat1[0])
      var lat1=this.THREE.MathUtils.degToRad(lonlat1[1])
      var lon2=this.THREE.MathUtils.degToRad(lonlat2[0])
      var lat2=this.THREE.MathUtils.degToRad(lonlat2[1])
      if(lon1==lon2){
      	if (lat2 >= lat1){
          return 180
        }else{
          return 0
        }
      }
      if (lat1 == lat2){
        if(lon2 > lon1 ){
          return 90
        }else if(lon2 < lon1){
          return -90
      	}
      }
      var a = this.THREE.MathUtils.radToDeg(Math.atan((lon2 - lon1) * Math.cos(lat2) / (lat2 - lat1)))
      if(lat2 > lat1){
        if(lon2 > lon1){
          return 180 - a
        }else{
          return 180 - (a + 360)
        }
      }else{
        return -a
      }
    },
    onClickPoint (event, pathStyle) {
      var e = event.target?event.target:event
      let index = e.properties.index
      let lushu = this.luShuArr[index]
      e.setPosition(new BMap.Point(0, 0))
      lushu.start((pointMarker) => {
        e.setTop(true)
        e.setPosition(pointMarker.getPosition())
        e.setRotation(pointMarker.getRotation())
        if (pathStyle.loop) {
          setTimeout(() => {
            this.onClickPoint(e, pathStyle)
          }, 300)
        }

      })
    },
    onClickMap (e) {
      if (e.overlay) {
        console.log(e);
        console.log('点击了 overlay');
      } else {
        if (this.infoWindow.isOpen()) {
          console.log('关闭 dialog');
          this.onCloseInfoWindow()
        } else {
          console.log('点击地图');
          this.$emit('on-click-map', e)
        }
      }
    },
    onClickMarker (e) {
      // e.domEvent.stopPropagation()
      console.log('点击标记点', e);
      this.currentInfo = e.target.properties
      if (this.currentInfo.showInfoWindow) {
        if (this.currentInfo.customInfoWindow) {
          this.infoWindow.setContent(this.currentInfo.customInfoWindow)
        } else {
          this.infoWindow.setContent(this.$refs['wh-baidu-infoWindow'])
        }
        this.map.openInfoWindow(this.infoWindow, e.point)
      }
      if (this.currentInfo.isInLine) {
        // const pointInLineList =
        this.checkPointIsInLine(e, this.currentInfo)
        // console.log(pointInLineList);
        // this.currentInfo.containPointLine = pointInLineList
      }
      this.$emit('on-click-marker', e, this.currentInfo, this.infoWindow)

    },
    checkPointIsInLine (e, properties) {
      var list = this.map.getOverlays()
      var arr = []
      let id = properties.id.split('-')[0]
      let pointPosition = properties.id.split('-')[1]
      for (var i = 0; i < list.length; i++) {

        // if (list[i].properties && list[i].properties.type == 'path') {
        //   if (list[i].properties.oldColor) {
        //     list[i].setStrokeColor(list[i].properties.oldColor)
        //   }
        // }
        // if (list[i].properties && list[i].properties.type == 'marker') {
        //   if (list[i].properties.oldIcon) {
        //     list[i].setIcon(list[i].properties.oldIcon)
        //     list[i].setOffset(new BMap.Size(0, 0))
        //   }
        // }
        // if (list[i].properties && list[i].properties.type == 'path' && list[i].properties.id == id) {

        //   arr.push(list[i])
        //   if (pointPosition == 0) {
        //     if (list[i-1]) {
        //       arr.push(list[i-1])
        //     }
        //   } else {
        //     if (list[i+1]) {
        //       arr.push(list[i+1])
        //     }
        //   }
        // }
        if (list[i].properties && list[i].properties.type == 'template') {
          this.map.removeOverlay(list[i])
        }
        if (list[i].properties && list[i].properties.type == 'path' && list[i].properties.id == id) {

          arr.push({
            path: list[i].getPath(),
            properties: list[i].properties
          })
          if (pointPosition == 0) {
            if (list[i-1]) {
              arr.push({
                path: list[i-1].getPath(),
                properties: list[i-1].properties
              })
            }
          } else {
            if (list[i+1]) {
              arr.push({
                path: list[i+1].getPath(),
                properties: list[i+1].properties
              })
            }
          }
        }


      }
      // properties.pathList = arr
      // properties.currentMarker = e.target.getPosition()
      const icon = new BMap.Icon(require('../assets/marker/marker-6.png'),
        new BMap.Size(28, 28),
        {
          imageSize: new BMap.Size(28, 28),
          imageOffset:  new BMap.Size(0, 0)
        }
      )
      var currentMarker = new BMap.Marker(e.target.getPosition(), {
        icon: icon,
        offset: new BMap.Size(0, -14)
      });
      currentMarker.properties = {
        ...properties,
        showInfoWindow: true,
        isInLine: false,
        type: 'template',
      }
      currentMarker.addEventListener('click', this.onClickMarker)
      this.map.addOverlay(currentMarker)
      for (var i = 0; i < arr.length; i++) {

        var path = new BMap.Polyline(arr[i].path, {
          strokeColor: 'red',
          strokeOpacity:1,
          strokeWeight: 5,
          enableMassClear:true,
        })
        path.properties = {
          ...arr[i].properties,
          showInfoWindow: true,
          highLightPoint: false,
          type: 'template',
        }
        path.addEventListener('click', this.onClickPath)
        this.map.addOverlay(path)
      }

      // var linesList = []
      // for (var i = 0; i < this.pathListArr.length; i++) {
      //   let k;
      //   if (this.pathListArr[i][0][0] === this.pathListArr[i][1][0]) {
      //     k = Infinity
      //   } else {
      //     k = (this.pathListArr[i][1][1]-this.pathListArr[i][0][1]) / (this.pathListArr[i][1][0] - this.pathListArr[i][0][0])
      //   }
      //   const b = this.pathListArr[i][0][1] - k * this.pathListArr[i][0][0]
      //   const distanceToLine = Math.abs((point.lat - k* point.lng - b)) / Math.sqrt(Math.pow(k, 2) + 1)
      //   if (distanceToLine < 0.0001) {
      //     console.log('点在直线上');
      //     linesList.push(this.pathListArr[i])
      //   }
      // }
      // return linesList


    },
    onClickPolygon (e) {
      // e.domEvent.stopPropagation()
      console.log('点击多边形', e);
      this.currentInfo = e.target.properties
      if (this.currentInfo.showInfoWindow) {
        if (this.currentInfo.customInfoWindow) {
          this.infoWindow.setContent(this.currentInfo.customInfoWindow)
        } else {
          this.infoWindow.setContent(this.$refs['wh-baidu-infoWindow'])
        }
        // this.infoWindow.show(e.coordinate);
        this.map.openInfoWindow(this.infoWindow, e.point)
      }
      this.$emit('on-click-polygon', e, this.currentInfo, this.infoWindow)
    },
    onClickPath (e) {
      this.currentInfo = e.target.properties
      if (this.currentInfo.showInfoWindow) {
        if (this.currentInfo.customInfoWindow) {
          this.infoWindow.setContent(this.currentInfo.customInfoWindow)
        } else {
          this.infoWindow.setContent(this.$refs['wh-baidu-infoWindow'])
        }
        // this.infoWindow.show(e.coordinate);
        this.map.openInfoWindow(this.infoWindow, e.point)
      }

      if (this.currentInfo.highLightPoint) {

        this.findPointFormPath(e, this.currentInfo)
      }
      this.$emit('on-click-path', e, this.currentInfo, this.infoWindow)
    },
    findPointFormPath (e, properties) {
      var list = this.map.getOverlays()
      var arr = []
      for (var i = 0; i < list.length; i++) {
        // if (list[i].properties && list[i].properties.type == 'path') {
        //   if (list[i].properties.oldColor) {
        //     list[i].setStrokeColor(list[i].properties.oldColor)
        //   }
        // }
        if (list[i].properties && list[i].properties.type == 'template') {
          this.map.removeOverlay(list[i])
        }
        if (list[i].properties && list[i].properties.type == 'marker') {
          let id = list[i].properties.id.split('-')[0]
          if (id == properties.id) {
            arr.push({
              position: list[i].getPosition(),
              properties: list[i].properties
            })
          }
        }
        // properties.currentPath = e.target
        // properties.pointList = arr
      }
      var path = new BMap.Polyline(e.target.getPath(), {
        strokeColor: 'red',
        strokeOpacity:1,
        strokeWeight: 5,
        enableMassClear:true,
      })
      path.properties = {
        ...properties,
        showInfoWindow: true,
        highLightPoint: false,
        type: 'template',
      }
      path.addEventListener('click', this.onClickPath)
      this.map.addOverlay(path)

      for (var i = 0; i < arr.length; i++) {
        const icon = new BMap.Icon(require('../assets/marker/marker-6.png'),
          new BMap.Size(28, 28),
          {
            imageSize: new BMap.Size(28, 28),
            imageOffset:  new BMap.Size(0, 0)
          }
        )
        var currentMarker = new BMap.Marker(arr[i].position, {
          icon: icon,
          offset: new BMap.Size(0, -14)
        });
        currentMarker.properties = {
          ...arr[i].properties,
          showInfoWindow: true,
          isInLine: false,
          type: 'template',
        }
        currentMarker.addEventListener('click', this.onClickMarker)
        this.map.addOverlay(currentMarker)
      }
    }
  },
}
</script>

<style scoped>
  .wh-baidu-wraper {
    width: 100%;
    height: 100%;
  }
  .wh-baidu {
    width: 100%;
    height: 100%;
  }
  .wh-baidu-infoWindow {
    width: 300px;
    left: -1000px;
    box-sizing: border-box;
    border-radius: 5px;
    overflow: hidden;
  }
  .wh-baidu-infoWindow-title {
    padding: 10px 16px;
    box-sizing: border-box;
    background: rgba(27,29,25, 0.95);
    color: #dbdbdb;
    font-weight: 500;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
  }
  .wh-baidu-infoWindow-title>p {
    flex-shrink: 0;
    font-size: 16px;
    margin: 0;
  }
  .wh-baidu-infoWindow-title>img {
    flex-shrink: 1;
    width: 20px;
    display: block;
    cursor: pointer;
  }
  .wh-baidu-infoWindow-content {
    padding: 10px 16px;
    box-sizing: border-box;
    color: #dbdbdb;
    text-align: left;
    font-weight: 400;
    background: rgba(39,40,34, 0.8);
    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;
  }
  .wh-baidu-infoWindow-place {
    height: 20px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
  }
  .wh-baidu-infoWindow-bottom {
    /* position: absolute; */
    width: 0;
    height: 0;
    margin-top: 20px;
    border-top: 20px solid rgba(39,40,34, 0.8);
    border-right: 20px solid transparent;
    border-left: 20px solid transparent;
    border-bottom: 20px solid transparent;
  }
  >>> .BMap_pop>div:nth-child(1),
  >>> .BMap_pop>div:nth-child(2),
  >>> .BMap_pop>div:nth-child(3),
  >>> .BMap_pop>div:nth-child(4),
  >>> .BMap_pop>div:nth-child(5),
  >>> .BMap_pop>div:nth-child(6),
  >>> .BMap_pop>div:nth-child(7),
  >>> .BMap_pop>div:nth-child(8),
  >>> .BMap_pop>img:nth-child(10),
  >>> .BMap_shadow {
    display: none;
  }
  >>> .BMap_pop>div:nth-child(9) {
    height: auto !important;
  }
  >>> .anchorBL {
    display: none;
  }
</style>
